<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        :root {
            --bg: #fff;
            --text-color: #222;
            --link-color: #0033cc;
        }

        :root .dark {
                --bg: #121212;
                --text-color: #eee;
                --link-color: #809fff;
        }

        body {
            --duration: 0.5s;
            --timing: ease;

            color: var(--text-color);
            background-color: var(--bg);
            /* 在模式切换过程中给color和background-color属性添加过渡效果 */
            transition: background-color var(--duration) var(--timing),
                color var(--duration) var(--timing);
        }
        body a {
            color: var(--link-color);
        }
        @media (prefers-color-scheme: dark) {
            :root {
                --bg: #121212;
                --text-color: #eee;
                --link-color: #809fff;
            }
            img {
                /* 在深色模式下图片的亮度比原来低点，对比度比原来高点，这样子图片的显示柔和一点且用户看起来舒服点 */
                filter: brightness(0.8) contrast(1.2);
            }
        }
    </style>
</head>
    <body>
        <button class="btn-toggle">切换模式</button>
        <h1>这里是标题</h1>
        <p>这里是内容。 测试的内容</p>
        <a href="#">一个超链接</a>
        <div>
            <img src="https://i2.wp.com/css-tricks.com/wp-content/uploads/2020/06/image-normal-1.png?resize=1102%2C780&ssl=1" />
        </div>
    </body>
    <script>
        const currentTheme = localStorage.getItem("theme");
        const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
        const btn = document.querySelector(".btn-toggle");

        const autoToggleTheme = (e) => {
            if (e.matches) {
                document.body.classList.add("dark");
            } else {
                document.body.classList.remove("dark");
            }
        };

        const handleToggleTheme = () => {
            if (prefersDarkScheme.onchange) prefersDarkScheme.onchange = null;
            document.body.classList.toggle("dark");
            let theme = "light";
            if (document.body.classList.contains("dark")) theme = "dark";
            localStorage.setItem("theme", theme);
        };

        // 如果没有用户偏好的模式的记录，自动跟随系统切换主题模式，反之使用用户偏好的模式
        if (!currentTheme) {
            prefersDarkScheme.onchange = autoToggleTheme;
        } else {
            document.body.classList.add(currentTheme);
        }
        btn.addEventListener("click", handleToggleTheme);

    </script>
</html>